<?php

namespace App\Library\Junda;

use App\Exceptions\ApicrzsExceptions;
use App\Library\Junda\src\JundaLogin;
use App\Modules\Admin\Entities\Log\AdminLoginLog;
use Illuminate\Support\Facades\Cache;

class JunDaApiClient
{

    public static $access_token='';
    public function __construct()
    {
        $this->access_token= Cache::get('login_junda_access_token');
        exit(json_encode(324));
    }
    function sendPostRequest($url, $data_string) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'X-AjaxPro-Method:ShowList',
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data_string))
        );
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    public static function sendRequest($url, $method = 'GET', $data = null,$islogin=false) {
        $access_token= Cache::get('login_junda_access_token');
        if (!$islogin) {
            if (!$access_token) {
                $access_token = JundaLogin::login();
            }
            $headers = ['Content-Type: application/json', 'Authorization: ' . $access_token];
        }else{
            $headers = ['Content-Type: application/json'];
        }
        $ch = curl_init();
        if ($method == 'GET'){
            // 如果提供了参数，则构建带参数的URL
            if (!empty($data)) {
                $url .= '?' . http_build_query($data);
            }
            curl_setopt($ch, CURLOPT_HEADER, false); // 不返回响应头信息
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);

        // 设置请求方法
        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        // 添加自定义头
        if (!empty($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        $response = curl_exec($ch);
        curl_close($ch);
        $object = json_decode($response,true);
        return $object;
    }


}
